Skip to content

rupeshv2121/Amulate-BMW-Group

Repository files navigation

Amulate BMW Group

An intelligent AI-powered productivity assistant with BMW-themed showcase, featuring calendar management, task tracking, and AI chat capabilities.


📋 Table of Contents

  1. Project Overview
  2. Key Features
  3. Technology Stack
  4. Architecture
  5. Prerequisites
  6. Installation & Setup
  7. Usage Guide
  8. Configuration
  9. API Documentation
  10. Development
  11. Troubleshooting

🎯 Project Overview

Amulate BMW Group is a full-stack productivity application featuring:

  • 📅 Google Calendar Integration - Natural language calendar management
  • Smart Task Management - AI-powered task parsing with deadline tracking
  • 🔔 Task Deadline System - Color-coded urgency indicators (Red/Orange/Yellow)
  • 👥 Real-time Collaboration - Share tasks and calendars with team members
  • 🚗 BMW Showcase - Interactive 3D BMW presentation with intro animation
  • 🎨 Modern UI - Dark/light theme with smooth animations

✨ Key Features

Task Management

  • AI-powered parsing: Create tasks from natural language (e.g., "Schedule a 2-hour coding session after lunch")
  • 🎯 Priority levels: Low, Medium, High with visual indicators
  • 🏷️ Categories: Organize tasks by category
  • ⏱️ Estimated time: Optional duration estimates
  • 📆 Deadline tracking: Set due dates with urgency indicators:
    • 🚨 Red: Less than 6 hours remaining
    • Orange: 6-24 hours remaining
    • ⏱️ Yellow: 1-3 days remaining
  • 🎙️ Voice input: Speech-to-text for hands-free task creation
  • 📤 Task sharing: Share tasks with other users via email (Under Maintenance)
  • 🔄 Real-time updates: Live synchronization across users

Calendar Integration

  • 📅 Google Calendar sync: View and manage Google Calendar events
  • 📝 Natural language: Create events with conversational commands
  • 🔄 Real-time refresh: Live calendar updates
  • 📍 Event details: View location, description, and time

Collaboration (Under Maintenance)

  • 👥 Share tasks: Assign tasks to team members
  • 📧 Email notifications: Automatic sharing notifications
  • 🔔 Real-time updates: Instant sync of shared items
  • 📋 Shared view: Dedicated tab for items shared with you

BMW Showcase

  • 🚗 Intro animation: Stunning BMW logo reveal with glowing effects
  • 🎨 Landing page: Professional BMW-themed presentation
  • 📱 Responsive design: Works on all devices
  • 🌙 Theme toggle: Dark and light modes

🛠️ Technology Stack

Frontend

  • Framework: React 18 with TypeScript
  • Build Tool: Vite 5
  • UI Components: shadcn/ui (built on Radix UI primitives)
  • Styling: Tailwind CSS 3 + CSS custom properties
  • Animations: Framer Motion
  • 3D Graphics: Spline, React Three Fiber
  • Routing: React Router DOM v6
  • State Management: React hooks + TanStack Query
  • Markdown: react-markdown with remark-gfm
  • Icons: Lucide React

Backend

  • API Framework: FastAPI (Python)
  • AI/LLM: LangGraph + Groq (Llama 3.1 8B Instant)
  • Calendar API: Google Calendar API (googleapis)
  • Database: Supabase PostgreSQL
  • Authentication: Supabase Auth
  • Real-time: Supabase Realtime subscriptions
  • Edge Functions: Supabase Edge Functions (Deno)

Database Schema

  • profiles - User profiles
  • tasks - Task management with deadline column
  • shared_tasks - Task sharing relationships
  • calendars - User calendar metadata
  • calendar_events - Calendar events
  • calendar_shares - Calendar sharing
  • notifications - User notifications

🏗️ Architecture

System Overview

┌────────────────────────────────────────────────────────────┐
│               Frontend (React + Vite)                      │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │  Landing    │  │  Dashboard   │  │  AI Chat     │      │
│  │  & BMW      │  │  (Tasks/Cal) │  │  Interface   │      │
│  └─────────────┘  └──────────────┘  └──────────────┘      │
└────────────┬────────────────────────────────────────────────┘
             │
             │ HTTP/REST + WebSocket
             │
   ┌─────────┴────────┬──────────────────────┐
   │                  │                      │
   ▼                  ▼                      ▼
┌─────────────┐  ┌─────────────┐  ┌──────────────────┐
│  Supabase   │  │  Calendar   │  │  Google Calendar │
│  (DB+Auth)  │  │  Agent API  │  │  API             │
│  + Edge Fn  │  │  (Python)   │  │                  │
└─────────────┘  └──────┬──────┘  └──────────────────┘
                        │
                        ▼
                 ┌──────────────┐
                 │  LangGraph   │
                 │  + Groq LLM  │
                 │  (Llama 3.1) │
                 └──────────────┘

Component Structure

Amulate-BMW-Group/
├── src/
│   ├── pages/
│   │   ├── Index.tsx           # Landing page with intro
│   │   ├── BMW.tsx              # BMW showcase animation
│   │   ├── Dashboard.tsx        # Main dashboard (tabs)
│   │   ├── Auth.tsx             # Authentication page
│   │   ├── Profile.tsx          # User profile
│   │   └── NotFound.tsx         # 404 page
│   │
│   ├── components/
│   │   ├── dashboard/
│   │   │   ├── AIChat.tsx                 # AI chat (Chat/Agent modes)
│   │   │   ├── TaskManager.tsx            # Task management UI
│   │   │   ├── GoogleCalendarView.tsx     # Calendar display
│   │   │   ├── AllCalendarsView.tsx       # Multi-calendar view
│   │   │   ├── SharedWithMe.tsx           # Shared items view
│   │   │   ├── ShareDialog.tsx            # Sharing interface
│   │   │   ├── CalendarActionAnimation.tsx # Action feedback
│   │   │   ├── TaskManagerWithAI.tsx      # AI task variant
│   │   │   └── VoiceInterface.tsx         # Voice input
│   │   │
│   │   ├── ui/                  # shadcn/ui components
│   │   ├── HeroSection.tsx
│   │   ├── FeaturesSection.tsx
│   │   ├── AIDemoSection.tsx
│   │   ├── Navigation.tsx
│   │   ├── Footer.tsx
│   │   └── ThemeToggle.tsx
│   │
│   ├── integrations/
│   │   ├── supabase/           # Supabase client setup
│   │   ├── calendarAgent.ts    # Calendar agent helpers
│   │   ├── calendarAgentConfig.ts
│   │   ├── calendarAgentService.ts  # Calendar API calls
│   │   └── taskAgentService.ts      # Task AI service
│   │
│   ├── hooks/
│   │   ├── useAuth.ts          # Authentication hook
│   │   ├── useNotifications.ts # Notifications hook
│   │   ├── use-toast.ts        # Toast notifications
│   │   └── use-mobile.tsx      # Mobile detection
│   │
│   └── lib/
│       └── utils.ts            # Utility functions
│
└── supabase/
    ├── migrations/             # Database migrations
    └── functions/              # Edge functions
        ├── ai-assistant/       # AI chat function
        └── send-share-notification/  # Sharing notifications

calender-agent-service/         # Backend Python service
├── app_langgraph.py           # FastAPI server
├── graph.py                   # LangGraph workflow
├── nodes.py                   # Agent nodes
├── state.py                   # State management
├── calendar_tools.py          # Calendar operations
├── google_apis.py             # Google API integration
├── clarification_agent.py     # User clarification
├── constraint_agent.py        # Constraint checking
└── requirements.txt           # Python dependencies

⚙️ Prerequisites

Required Software

  1. Python 3.10+

  2. Git

Required Accounts & API Keys

  1. Supabase Account (Database & Auth)

  2. Google Cloud Account (Calendar API)

  3. Groq API Key (LLM for agents)

  4. OpenAI API Key (Optional - for Chat mode)


🚀 Installation & Setup

Part 1: Frontend Setup

1. Clone Repository

git clone <your-repository-url>
cd Amulate-BMW-Group

2. Install Dependencies

npm install

This installs React, TypeScript, Vite, Tailwind CSS, shadcn/ui, Supabase client, and all other dependencies.

3. Configure Environment Variables

Create .env file in the root directory:

# Supabase Configuration
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=your-anon-public-key
VITE_SUPABASE_PROJECT_ID=your-project-id

# Backend Services
VITE_CALENDAR_AGENT_URL=http://localhost:8000
VITE_TASK_AGENT_URL=http://localhost:8000

# Optional: Google Gemini (if using Gemini mode)
VITE_GEMINI_API_KEY=your-gemini-api-key

Getting Supabase Credentials:

  1. Go to https://supabase.com/dashboard
  2. Create new project or select existing
  3. Settings → API
  4. Copy:
    • Project URL → VITE_SUPABASE_URL
    • anon/public key → VITE_SUPABASE_PUBLISHABLE_KEY
    • Project ID → VITE_SUPABASE_PROJECT_ID

4. Set Up Supabase Database

Option A: Using Supabase CLI (Recommended)

# Install Supabase CLI
npm install -g supabase

# Login
supabase login

# Link to your project
supabase link --project-ref your-project-ref

# Push migrations
supabase db push

Option B: Manual Migration

Copy SQL from migration files in supabase/migrations/ and run them in Supabase SQL Editor:

  • 20251208082529_*.sql - Initial schema
  • 20251212204627_*.sql - Calendar shares
  • 20251212205225_*.sql - Task updates
  • 20251227105113_*.sql - Notifications
  • 20251229000000_add_task_deadline.sql - Task deadlines
  • 20251229000000_fix_shared_task_policies.sql - RLS fixes
  • 20251229120000_add_deadline_to_tasks.sql - Deadline indices

This creates tables: profiles, tasks, shared_tasks, calendars, calendar_events, calendar_shares, notifications

5. Configure Supabase Edge Functions (Optional)

If using AI chat features:

# Add secrets in Supabase Dashboard → Edge Functions → Secrets
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
OPENAI_API_KEY=your-openai-key

# Deploy functions
supabase functions deploy ai-assistant
supabase functions deploy send-share-notification

6. Start Frontend

npm run dev

Frontend available at: http://localhost:8080


Part 2: Backend Setup (Calendar & Task Agents) : https://github.com/rupeshv2121/AI_agent_service

1. Navigate to Backend

cd calender-agent-service

2. Create Python Virtual Environment

# Windows
python -m venv venv
venv\Scripts\activate

# Linux/Mac
python3 -m venv venv
source venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

This installs FastAPI, LangGraph, LangChain, Groq SDK, Google APIs, and more.

4. Google Calendar API Setup

A. Enable API in Google Cloud

  1. Go to https://console.cloud.google.com/
  2. Create new project (e.g., "Amulate Calendar")
  3. APIs & Services → Library
  4. Search "Google Calendar API" → Enable

B. Create OAuth 2.0 Credentials

  1. APIs & Services → Credentials
  2. Create Credentials → OAuth client ID
  3. Configure consent screen if needed:
    • User Type: External
    • Add your email as test user
    • Scopes: https://www.googleapis.com/auth/calendar
  4. Application type: Desktop app
  5. Download JSON
  6. Save as client_secret.json in calender-agent-service/

C. Verify client_secret.json Format

Ensure redirect URIs include:

{
  "installed": {
    "redirect_uris": [
      "http://localhost:8000",
      "urn:ietf:wg:oauth:2.0:oob"
    ]
  }
}

5. Configure Backend Environment

Create .env file in calender-agent-service/:

# Groq API Key (required for AI agents)
GROQ_API_KEY=your-groq-api-key

# Server Configuration
PORT=8000
HOST=0.0.0.0

# Optional: OpenAI (alternative LLM)
OPENAI_API_KEY=your-openai-key

Get Groq API Key:

  1. https://console.groq.com/
  2. Sign up/Login
  3. API Keys → Create API Key
  4. Copy to .env

6. First-Time Authorization

python app_langgraph.py
  • Browser opens automatically
  • Sign in with Google account
  • Grant calendar permissions
  • Authorization complete
  • Token saved to token_calender_v3.pickle

7. Start Backend Server

python app_langgraph.py

Backend available at: http://localhost:8000

Verify:

curl http://localhost:8000/health

Should return:

{"status": "healthy"}

📖 Usage Guide

Landing Page

Navigate to http://localhost:8080 to see:

  • Intro Animation: Animated BMW logo reveal with glowing effects
  • Hero Section: BMW presentation with interactive elements
  • AI Demo Section: Preview of AI assistant capabilities
  • Features Section: Overview of key features
  • Navigation: Access to Auth and BMW showcase

Authentication

  1. Click "Sign In" in navigation
  2. Create account or sign in with email
  3. Verify email (check Supabase Auth settings)
  4. Redirected to Dashboard

Dashboard Overview

Dashboard has 4 tabs:

  1. Tasks - Task management
  2. Calendars - Google Calendar integration
  3. Shared - Items shared with you (Under Maintenance)
  4. AI Chat - AI assistant (Chat & Agent modes)

Task Management

Creating Tasks

Manual Creation:

  1. Go to Tasks tab
  2. Click "+" button
  3. Fill in:
    • Title (required)
    • Priority: Low/Medium/High
    • Category
    • Estimated time (optional)
    • Deadline (optional)
  4. Click "Add Task"

AI-Powered Creation:

  1. Click sparkle icon (⚡)
  2. Type natural language:
    • "Schedule 2-hour coding session"
    • "Add urgent task: Fix auth bug"
    • "Create task to review docs by Friday"
  3. AI extracts priority, category, time, and deadline
  4. Review and save

Voice Input:

  • Click microphone icon in task input
  • Speak your task
  • Works in both manual and AI modes

Managing Tasks

  • Complete: Click checkbox
  • Delete: Click trash icon
  • View details: See priority, category, time estimate
  • Urgency indicators:
    • 🚨 Red badge: < 6 hours until deadline
    • ⏰ Orange badge: 6-24 hours remaining
    • ⏱️ Yellow badge: 1-3 days remaining

Sharing Tasks

  1. Select a task
  2. Click share icon
  3. Enter recipient's email
  4. Recipient receives notification
  5. Task appears in their "Shared" tab

Calendar Integration

Viewing Calendars

  1. Go to Calendars tab
  2. See all your Google calendars
  3. Events displayed with:
    • Title
    • Date & time
    • Location (if set)
    • Calendar name

Managing Events

Via AI Chat (Agent Mode):

  1. Go to AI Chat tab
  2. Select "Agent" mode (Cpu icon)
  3. Type commands like:
    • "Schedule meeting tomorrow at 2pm"
    • "Show my events for next week"
    • "Create event: Team sync on Friday 3pm"
  4. Agent uses LangGraph + Google Calendar API

Refreshing Calendars

  • Click refresh icon in calendar view
  • Real-time sync with Google Calendar

AI Chat Assistant

Chat Modes

The AI Chat has 2 modes (switch via tabs):

  1. Chat Mode (💬 MessageSquare icon) (Under Maintenance)

    • General productivity assistant
    • Uses OpenAI GPT via Supabase Edge Function
    • Best for: Questions, advice, general tasks
  2. Agent Mode (🤖 Cpu icon)

    • Calendar & task management
    • Uses LangGraph + Groq (Llama 3.1)
    • Understands calendar intents
    • Can create/modify calendar events
    • Natural language task parsing

Using Chat

  1. Type message in input box
  2. Optional: Attach files (images, PDFs, text)
  3. Optional: Use voice input (microphone icon)
  4. Send message
  5. Watch streaming response (character-by-character)

Supported Features:

  • 📎 File attachments (images, documents)
  • 🎙️ Voice input
  • 📝 Markdown responses
  • ⚡ Streaming text
  • 🔄 Conversation history

Examples

Agent Mode (Calendar):

  • "Create meeting with Sarah tomorrow at 10am"
  • "Show my schedule for today"
  • "Add event: Dentist appointment Friday 2pm"
  • "List all my calendars"

Chat Mode (General):

  • "Help me prioritize my tasks"
  • "Explain SOLID principles"
  • "How do I improve productivity?"

Task Intent (both modes):

  • "Add task: Review pull requests"
  • "Schedule 30min coding session"
  • "Remind me to call John by 5pm"

Shared Items

View tasks and calendars shared with you:

  1. Go to "Shared" tab
  2. Two sub-tabs:
    • Tasks: Tasks assigned to you
    • Calendars: Calendars you have access to
  3. Real-time updates via Supabase Realtime
  4. See who shared each item
  5. Complete shared tasks (updates for everyone)

Profile & Settings

  1. Click user icon in dashboard header
  2. View/edit profile
  3. Manage account settings
  4. Sign out

⚙️ Configuration

Frontend Configuration

Tailwind CSS Customization

File: tailwind.config.ts

// Customize colors
theme: {
  extend: {
    colors: {
      primary: {
        DEFAULT: "hsl(var(--primary))",
        foreground: "hsl(var(--primary-foreground))",
      },
      // Add custom BMW colors
      bmw: {
        blue: "#1C69D4",
        black: "#000000",
        white: "#FFFFFF",
      }
    }
  }
}

Vite Configuration

File: vite.config.ts

export default defineConfig({
  server: {
    port: 8080,        // Change port
    host: "::",        // Listen on all interfaces
    proxy: {           // Add API proxy
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
      }
    }
  },
  build: {
    outDir: 'dist',    // Output directory
    sourcemap: true,   // Generate sourcemaps
  }
});

Backend Configuration

Calendar Agent Settings

File: calender-agent-service/state.py

class GraphState(TypedDict):
    messages: Annotated[Sequence[BaseMessage], add_messages]
    intent: str          # Detected intent
    action: str          # Action to perform
    calendar_name: str   # Target calendar
    # Add custom fields as needed

LLM Configuration

File: calender-agent-service/graph.py

# Change LLM model
llm = ChatGroq(
    model="mixtral-8x7b-32768",  # or "llama-3.1-70b-versatile"
    temperature=0.7,              # Creativity (0-1)
    max_tokens=4096,             # Response length
)

API Settings

File: app_langgraph.py

# CORS configuration
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8080"],  # Add production URLs
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

📡 API Documentation

Calendar Agent API

Base URL: http://localhost:8000 (development)

Health Check

GET /health

Response:

{
  "status": "healthy"
}

Calendar Operations

POST /calendar
Content-Type: application/json

Request:

{
  "message": "Schedule meeting tomorrow at 2pm",
  "thread_id": "optional-uuid",
  "history": [
    {"role": "user", "content": "previous message"},
    {"role": "assistant", "content": "previous response"}
  ],
  "user_decision": null
}

Response:

{
  "response": "✅ Meeting scheduled for Dec 29, 2025 at 2:00 PM",
  "thread_id": "conversation-uuid",
  "state": {
    "intent": "calendar_management",
    "action": "create_event",
    "calendar_name": "Primary",
    "error": null
  },
  "debug_info": {
    "processing_time_ms": 1234
  }
}

Supported Actions:

  • create_event - Create calendar event
  • list_events - Retrieve events
  • update_event - Modify event
  • delete_event - Remove event
  • list_calendars - Get all calendars
  • create_calendar - Create new calendar

List Calendars

GET /calendars

Response:

{
  "success": true,
  "calendars": [
    {
      "id": "primary",
      "name": "My Calendar",
      "description": "Primary calendar",
      "accessRole": "owner",
      "primary": true
    }
  ]
}

Get Calendar Events

GET /events/{calendar_id}?timeMin=2025-01-01T00:00:00Z&timeMax=2025-12-31T23:59:59Z

Response:

{
  "success": true,
  "events": [
    {
      "id": "event-id",
      "summary": "Team Meeting",
      "start": {"dateTime": "2025-01-15T10:00:00Z"},
      "end": {"dateTime": "2025-01-15T11:00:00Z"},
      "location": "Conference Room A"
    }
  ]
}

Task Agent API

Base URL: http://localhost:8000 (development)

Parse Task

POST /api/task-agent/parse
Content-Type: application/json

Request:

{
  "message": "Schedule 2-hour coding session by Friday",
  "existing_tasks": []
}

Response:

{
  "conversational_response": "Task created successfully!",
  "parsed_task": {
    "title": "Coding session",
    "priority": "medium",
    "category": "Work",
    "duration": "2 hours",
    "estimated_time": "2h",
    "deadline": "2025-12-29T23:59:59Z"
  },
  "context": "Task scheduling",
  "estimated_effort": "2 hours"
}

Summarize Tasks

POST /api/task-agent/summarize
Content-Type: application/json

Request:

[
  {
    "title": "Review code",
    "priority": "high",
    "category": "Work"
  }
]

Response:

{
  "summary": "You have 1 high-priority task...",
  "task_count": 1,
  "breakdown": {
    "high": 1
  }
}

Supabase Database Schema

Tasks Table

CREATE TABLE tasks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  priority TEXT CHECK (priority IN ('low', 'medium', 'high')),
  category TEXT,
  completed BOOLEAN DEFAULT false,
  estimated_time TEXT,
  deadline TIMESTAMPTZ,
  reminder_sent BOOLEAN DEFAULT false,
  created_at TIMESTAMPTZ DEFAULT now(),
  updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE INDEX idx_tasks_user_id ON tasks(user_id);
CREATE INDEX idx_tasks_deadline ON tasks(deadline) WHERE deadline IS NOT NULL;
CREATE INDEX idx_tasks_upcoming_deadlines ON tasks(user_id, deadline, completed) 
  WHERE deadline IS NOT NULL AND completed = false;

Shared Tasks Table

CREATE TABLE shared_tasks (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  task_id UUID REFERENCES tasks(id) ON DELETE CASCADE,
  shared_by UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  shared_with UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  created_at TIMESTAMPTZ DEFAULT now()
);

RLS Policies

  • Users can view/modify only their own tasks
  • Users can view tasks shared with them
  • Task sharing requires explicit permission

💻 Development

Project Structure

Amulate-BMW-Group/
├── src/
│   ├── pages/              # Route pages
│   ├── components/         # React components
│   │   ├── dashboard/     # Dashboard components
│   │   └── ui/            # shadcn/ui primitives
│   ├── integrations/      # API integrations
│   ├── hooks/             # Custom React hooks
│   └── lib/               # Utilities
├── supabase/
│   ├── migrations/        # Database migrations
│   └── functions/         # Edge functions
└── public/                # Static assets

calender-agent-service/    # Python backend
├── app_langgraph.py      # FastAPI server
├── graph.py              # LangGraph workflow
├── nodes.py              # Agent logic
├── calendar_tools.py     # Calendar operations
└── google_apis.py        # Google API client

Adding New Features

Frontend Component

// src/components/MyFeature.tsx
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";

export const MyFeature = () => {
  const { user } = useAuth();
  
  return (
    <div>
      <h2>My Feature</h2>
      <Button>Click Me</Button>
    </div>
  );
};

Backend Endpoint

# calender-agent-service/app_langgraph.py
@app.post("/api/my-feature")
async def my_feature(data: dict):
    """Custom endpoint"""
    result = process_data(data)
    return {"success": True, "result": result}

Code Style

TypeScript

// Use TypeScript types
interface TaskProps {
  title: string;
  priority: "low" | "medium" | "high";
  onComplete: () => void;
}

// Use functional components with hooks
export const TaskItem = ({ title, priority, onComplete }: TaskProps) => {
  const [isLoading, setIsLoading] = useState(false);
  
  return (
    <Button onClick={onComplete} disabled={isLoading}>
      {title}
    </Button>
  );
};

Python

# Use type hints
from typing import Optional
from datetime import datetime

def create_event(
    title: str,
    start_time: datetime,
    end_time: datetime,
    calendar_id: Optional[str] = None
) -> dict:
    """Create calendar event.
    
    Args:
        title: Event title
        start_time: Start datetime
        end_time: End datetime
        calendar_id: Optional calendar ID
        
    Returns:
        Created event details
    """
    pass

Debugging

Frontend

  • React DevTools: Inspect components
  • Console: console.log(), console.table()
  • Network Tab: Monitor API calls

Backend

  • FastAPI Docs: Visit http://localhost:8000/docs
  • Logging: Use logging module
  • Debugger: breakpoint() or pdb.set_trace()

│ │ │ └── Profile │ └── Profile Settings


#### Backend Service Architecture

Calendar Agent Service │ ├── app_langgraph.py (FastAPI server) │ ├── /health (Health check) │ ├── /calendar (Main endpoint) │ └── CORS middleware │ ├── graph.py (LangGraph workflow) │ ├── classify_node │ ├── calendar_node │ ├── reformulate_node │ └── general_node │ ├── nodes.py (Node implementations) │ ├── IntentClassifier │ ├── CalendarManager │ └── ResponseGenerator │ ├── calendar_tools.py (Google Calendar operations) │ ├── create_event() │ ├── list_events() │ ├── update_event() │ ├── delete_event() │ └── create_calendar() │ ├── google_apis.py (OAuth & API client) │ └── create_service() │ └── state.py (State management) └── GraphState (TypedDict)


### Adding New Features

#### Example: Add New Calendar View

1. **Create Component**:
```typescript
// src/components/dashboard/WeeklyView.tsx
import { useState } from 'react';

export const WeeklyView = () => {
  const [weekStart, setWeekStart] = useState(new Date());
  
  return (
    <div className="weekly-calendar">
      {/* Implementation */}
    </div>
  );
};
  1. Add to Dashboard:
// src/pages/Dashboard.tsx
import { WeeklyView } from '@/components/dashboard/WeeklyView';

// Add to tabs
<Tabs>
  <TabsList>
    <TabsTrigger value="weekly">Weekly</TabsTrigger>
  </TabsList>
  <TabsContent value="weekly">
    <WeeklyView />
  </TabsContent>
</Tabs>
  1. Update Types (if needed):
// src/types/calendar.ts
export interface WeekView {
  startDate: Date;
  endDate: Date;
  events: Event[];
}

Code Style Guide

TypeScript/React

// ✅ Good
interface Props {
  userId: string;
  onComplete: () => void;
}

export const TaskItem = ({ userId, onComplete }: Props) => {
  const [isLoading, setIsLoading] = useState(false);
  
  const handleClick = async () => {
    setIsLoading(true);
    await completeTask(userId);
    onComplete();
    setIsLoading(false);
  };
  
  return <Button onClick={handleClick} disabled={isLoading} />;
};

// ❌ Bad - no types, unclear naming
export const Item = ({ id, cb }) => {
  const [loading, setLoading] = useState(false);
  // ...
};

Python

# ✅ Good
from typing import List, Optional
from datetime import datetime

def create_event(
    title: str,
    start_time: datetime,
    end_time: datetime,
    calendar_id: Optional[str] = None
) -> dict:
    """Create a calendar event.
    
    Args:
        title: Event title
        start_time: Event start datetime
        end_time: Event end datetime
        calendar_id: Optional calendar ID (uses primary if None)
        
    Returns:
        dict: Created event details
    """
    # Implementation
    pass

# ❌ Bad - no types, no docstring
def create_event(title, start, end, cal=None):
    pass

Testing

Frontend Tests (React Testing Library)

// src/components/__tests__/TaskItem.test.tsx
import { render, screen, fireEvent } from '@testing-library/react';
import { TaskItem } from '../TaskItem';

describe('TaskItem', () => {
  it('renders task title', () => {
    render(<TaskItem title="Test Task" status="todo" />);
    expect(screen.getByText('Test Task')).toBeInTheDocument();
  });
  
  it('calls onComplete when checkbox clicked', () => {
    const onComplete = jest.fn();
    render(<TaskItem title="Test" onComplete={onComplete} />);
    
    fireEvent.click(screen.getByRole('checkbox'));
    expect(onComplete).toHaveBeenCalledTimes(1);
  });
});

Backend Tests (pytest)

# tests/test_calendar_tools.py
import pytest
from calendar_tools import create_event
from datetime import datetime, timedelta

def test_create_event():
    """Test event creation"""
    start = datetime.now()
    end = start + timedelta(hours=1)
    
    event = create_event(
        title="Test Meeting",
        start_time=start,
        end_time=end
    )
    
    assert event["summary"] == "Test Meeting"
    assert "id" in event

Debugging Tips

Frontend Debugging

  1. React DevTools:

    • Install Chrome extension
    • Inspect component props/state
    • Track re-renders
  2. Console Logging:

console.log('User data:', user);
console.table(tasks); // For arrays
console.error('API Error:', error);
  1. Network Tab:
    • Monitor API calls
    • Check request/response
    • Verify headers

Backend Debugging

  1. FastAPI Docs:

    • Visit http://localhost:8000/docs
    • Interactive API testing
    • See request/response schemas
  2. Python Debugger:

import pdb; pdb.set_trace()  # Breakpoint
# or
breakpoint()  # Python 3.7+
  1. Logging:
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.debug("Processing request: %s", request_data)
logger.error("Failed to create event", exc_info=True)

� Troubleshooting

Frontend Issues

Problem: Module not found errors

Solution:

# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

Problem: Supabase authentication not working

Solution:

  1. Verify .env has correct keys
  2. Check Supabase project is active
  3. Verify email confirmation in Auth settings
  4. Clear browser localStorage

Problem: Calendar not syncing

Solution:

  1. Check backend is running: http://localhost:8000/health
  2. Verify VITE_CALENDAR_AGENT_URL in .env
  3. Check browser console for errors
  4. Ensure Google Calendar token is valid

Backend Issues

Problem: ModuleNotFoundError in Python

Solution:

# Activate virtual environment
source venv/bin/activate  # Linux/Mac
venv\Scripts\activate     # Windows

# Reinstall dependencies
pip install -r requirements.txt

Problem: Task deadlines not saving

Solution:

# Apply database migrations
cd Amulate-BMW-Group
supabase db push

# Verify in Supabase Dashboard → Database → Migrations

Problem: Shared tasks not working

Solution:

  1. Run RLS policy fix migration
  2. Check Supabase logs for policy errors
  3. Verify shared_tasks table exists

Problem: Google Calendar unauthorized

Solution:

# Delete token and re-authorize
rm token_calender_v3.pickle
python app_langgraph.py
# Complete authorization flow

Problem: GROQ_API_KEY not found

Solution:

# Verify .env file
cat .env  # Linux/Mac
type .env  # Windows

# Ensure format:
GROQ_API_KEY=gsk_...

Common Errors

Port Already in Use

# Find process using port 8000 (Windows)
netstat -ano | findstr :8000
taskkill /PID <pid> /F

# Linux/Mac
lsof -ti:8000 | xargs kill -9

CORS Errors

Update app_langgraph.py:

allow_origins=[
    "http://localhost:8080",
    "http://localhost:5173",  # Vite default
    "https://your-production-domain.com"
]

Database Connection Issues

  1. Check Supabase project status
  2. Verify API keys in .env
  3. Check network/firewall
  4. Try restarting Supabase project

📝 License

This project is for educational and demonstration purposes.


🤝 Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

📧 Support

For issues and questions:


Built with ❤️ using React, TypeScript, Python, LangGraph, and Supabase

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages