Skip to content

ashutoshkarna03/purchase-data-analytics-graphql

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI GraphQL Purchase Data System

A comprehensive purchase data management system built with FastAPI and GraphQL, featuring robust schema design for e-commerce applications.

🚀 Features

  • Comprehensive Purchase Tracking - Complete order management with multiple status tracking
  • Customer Management - Detailed customer profiles with address and preference management
  • Product Catalog - Full product management with inventory tracking
  • Financial Tracking - Multi-currency support, tax, shipping, and discount management
  • Marketing Analytics - UTM tracking, source attribution, and campaign analytics
  • Fraud Prevention - Risk scoring and fraud detection capabilities
  • GraphQL API - Flexible, efficient data querying with GraphQL
  • Historical Data - Product snapshots preserve pricing and product info at purchase time

📋 Table of Contents

🛠 Installation

Prerequisites

  • Python 3.8+
  • PostgreSQL 12+
  • pip or poetry

Install Dependencies

# Clone the repository
git clone <repository-url>
cd fastapi-graphql

# Install dependencies
pip install -r requirements.txt

# Or using poetry
poetry install

🚀 Quick Start

1. Environment Setup

Create a .env file in the root directory:

DATABASE_URL=postgresql://username:password@localhost:5432/fastapi_graphql
DEBUG=True
SECRET_KEY=your-secret-key-here

2. Database Setup

# Create PostgreSQL database
createdb fastapi_graphql

# Run the application (this will create tables automatically)
python -m app.main

3. Start the Server

# Using uvicorn directly
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Or using Python
python -m app.main

4. Access the Application

📊 Schema Overview

The system consists of four main models:

Core Models

Model Description Key Features
Customer Customer profiles and information Address management, marketing preferences
Product Product catalog and inventory SKU tracking, pricing, inventory management
Purchase Main order/purchase records Status tracking, payments, shipping
PurchaseItem Individual line items within orders Quantity, pricing, fulfillment tracking

Key Relationships

Customer (1) ←→ (Many) Purchase
Product (1) ←→ (Many) PurchaseItem
Purchase (1) ←→ (Many) PurchaseItem

📖 API Documentation

GraphQL Endpoint

Endpoint: /graphql

Available Queries

# Get all customers
customers {
  id
  firstName
  lastName
  email
  isActive
}

# Get specific customer
customer(id: 1) {
  id
  firstName
  lastName
  email
  purchases {
    orderNumber
    totalAmount
    status
  }
}

# Get all products
products {
  id
  name
  sku
  price
  stockQuantity
}

# Get all purchases
purchases {
  id
  orderNumber
  totalAmount
  status
  customer {
    firstName
    lastName
  }
  items {
    quantity
    unitPrice
    product {
      name
    }
  }
}

Available Mutations

# Create a new customer
mutation {
  createCustomer(
    firstName: "John"
    lastName: "Doe"
    email: "[email protected]"
    phone: "+1234567890"
  ) {
    customer {
      id
      firstName
      lastName
      email
    }
  }
}

# Create a new product
mutation {
  createProduct(
    name: "Premium Widget"
    sku: "WIDGET-001"
    price: 29.99
    description: "A high-quality widget"
  ) {
    product {
      id
      name
      sku
      price
    }
  }
}

🗄️ Database Setup

Using PostgreSQL

  1. Install PostgreSQL:

    # macOS
    brew install postgresql
    
    # Ubuntu
    sudo apt-get install postgresql postgresql-contrib
  2. Create Database:

    createdb fastapi_graphql
  3. Update Connection String:

    DATABASE_URL=postgresql://username:password@localhost:5432/fastapi_graphql

Database Migration (Optional)

For production environments, consider using Alembic for migrations:

# Initialize Alembic
alembic init alembic

# Create migration
alembic revision --autogenerate -m "Initial migration"

# Apply migration
alembic upgrade head

🔍 GraphQL Examples

Complex Query Example

query GetPurchaseDetails {
  purchases {
    id
    orderNumber
    purchaseDate
    status
    totalAmount
    currency
    
    customer {
      firstName
      lastName
      email
    }
    
    items {
      quantity
      unitPrice
      totalPrice
      
      product {
        name
        sku
        category
      }
    }
    
    # Payment information
    paymentStatus
    paymentMethod
    
    # Shipping information
    shippingCity
    shippingCountry
    trackingNumber
  }
}

Filter by Order Status

query GetPendingOrders {
  purchases(status: "PENDING") {
    orderNumber
    totalAmount
    customer {
      email
    }
  }
}

⚙️ Environment Configuration

Create a .env file with the following variables:

# Database Configuration
DATABASE_URL=postgresql://username:password@localhost:5432/fastapi_graphql

# Application Configuration
APP_NAME=FastAPI GraphQL Purchase System
APP_VERSION=1.0.0
DEBUG=True

# Security
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# CORS Settings
ALLOWED_ORIGINS=["http://localhost:3000", "http://localhost:8000"]

# Payment Gateway (Example)
STRIPE_SECRET_KEY=sk_test_your_stripe_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_key

# Email Configuration (Optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=[email protected]
SMTP_PASSWORD=your-app-password

🔧 Development

Project Structure

fastapi-graphql/
├── app/
│   ├── __init__.py
│   ├── main.py                 # FastAPI application
│   ├── schema.py              # GraphQL schema
│   └── models/
│       ├── __init__.py
│       ├── base.py            # Database configuration
│       ├── customer.py        # Customer model
│       ├── product.py         # Product model
│       └── purchase.py        # Purchase models
├── requirements.txt           # Dependencies
├── README.md                 # This file
├── PURCHASE_SCHEMA_DOCUMENTATION.md  # Detailed schema docs
└── .env.example              # Environment template

Running Tests

# Install test dependencies
pip install pytest pytest-asyncio

# Run tests
pytest

Code Formatting

# Install formatting tools
pip install black isort

# Format code
black .
isort .

📈 Performance Considerations

Database Indexing

The schema includes strategic indexes on:

  • Customer email (unique)
  • Product SKU (unique)
  • Purchase order_number (unique)
  • Purchase status
  • Foreign key relationships

GraphQL Query Optimization

  • Use field selection to only fetch required data
  • Implement DataLoader for N+1 query prevention
  • Consider query complexity limits for production

🔒 Security Features

  • Risk Scoring: Built-in fraud detection with risk scoring
  • Payment Security: Secure payment gateway integration support
  • Data Validation: Comprehensive input validation with Pydantic
  • CORS Configuration: Configurable CORS settings

🚀 Deployment

Docker Deployment

FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
EXPOSE 8000

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Environment Variables for Production

DATABASE_URL=postgresql://user:pass@db:5432/production_db
DEBUG=False
SECRET_KEY=production-secret-key
ALLOWED_ORIGINS=["https://yourdomain.com"]

📚 Additional Resources

🤝 Contributing

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

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

📞 Support

For support, email [email protected] or create an issue in this repository.


Built with ❤️ using FastAPI and GraphQL

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages