Skip to content

ucsandman/Health-Achievement-Rewards

Repository files navigation

Health Achievement Rewards System

Turn your fitness achievements into real rewards. Walk 10,000 steps, unlock an Amazon purchase.

Overview

The Health Achievement Rewards System is a complete three-tier application that gamifies fitness by connecting Apple Health data to Amazon purchases. Users set achievement goals (e.g., "10,000 steps per day"), and when they achieve them, they unlock the ability to purchase items from Amazon within a specified budget.

How It Works

┌─────────────────┐
│   iOS App       │ Your fitness data from Apple Health
│   (HealthKit)   │
└────────┬────────┘
         │ Syncs health data
         ▼
┌─────────────────────────────────┐
│   FastAPI Backend               │ Evaluates achievements
│   (PostgreSQL + Redis)          │ Manages rewards
└────────┬────────────────────────┘
         │ Provides rewards
         ▼
┌─────────────────┐
│ Chrome Extension│ One-click purchase on Amazon
└─────────────────┘

User Flow:

  1. Set achievement goal: "Walk 10,000 steps daily to earn a $25 Amazon purchase"
  2. iOS app automatically syncs your health data from Apple Health
  3. Backend evaluates your progress and triggers achievement when goal is met
  4. Chrome extension shows a banner on Amazon product pages
  5. Click "Use Reward" to assign your achievement to a product
  6. Purchase the item and track your reward history

System Components

1. Backend API (FastAPI)

  • Location: health-rewards-backend/
  • Tech Stack: Python 3.12, FastAPI, PostgreSQL, Redis
  • Purpose: Central API for authentication, health data processing, rule evaluation, and reward management
  • Key Features:
    • JWT authentication
    • Health data ingestion and storage
    • Customizable achievement rules with streak tracking
    • Amazon Product Advertising API integration
    • Email and web push notifications
    • Real-time rule evaluation

2. iOS App (SwiftUI)

  • Location: ios-app/
  • Tech Stack: Swift 5.9+, SwiftUI, HealthKit
  • Purpose: Native iOS app for automatic health data syncing
  • Key Features:
    • Automatic HealthKit integration
    • Real-time health dashboard
    • Achievement tracking with progress visualization
    • Secure Keychain-based authentication
    • Background data sync

3. Chrome Extension

  • Location: chrome-extension/
  • Tech Stack: JavaScript, Chrome Extension APIs
  • Purpose: Amazon integration for one-click reward redemption
  • Key Features:
    • Detects Amazon product pages
    • Injects reward UI with purple gradient banner
    • One-click reward application
    • Purchase tracking
    • Real-time stats dashboard

4. Web Dashboard (Next.js)

  • Location: health-rewards-website/
  • Tech Stack: Next.js 16, React 19, TypeScript, Tailwind CSS, Radix UI
  • Purpose: Web dashboard for managing achievements, rewards, and analytics
  • Key Features:
    • Achievement creation and management with multi-step wizard
    • Reward approval workflow and purchase tracking
    • Health analytics and trends visualization
    • Streak and tier multiplier display
    • User settings and profile management
    • Responsive design with mobile navigation
    • Marketing landing pages

Quick Start

See QUICKSTART.md for a complete setup guide.

5-Minute Setup (Local Development):

# 1. Start the backend
cd health-rewards-backend
docker-compose up -d
# Backend runs at http://localhost:8000

# 2. Start the web dashboard
cd health-rewards-website
npm install && npm run dev
# Website runs at http://localhost:3000

# 3. Load Chrome Extension
# Open chrome://extensions/ → Enable Developer mode → Load unpacked → Select chrome-extension/

# 4. Build iOS App (requires Xcode on Mac)
# Open ios-app/HealthRewards.xcodeproj in Xcode
# Connect iPhone → Run (⌘R)

Features

Achievement System

  • Flexible Rules: Create custom achievement goals with various health metrics
  • Supported Metrics: Steps, active calories, exercise minutes, distance
  • Periods: Daily, weekly, monthly, or streak-based
  • Operators: Greater than, greater than or equal, equal to, streak count
  • Automatic Triggering: Backend evaluates rules in real-time when data syncs
  • Duplicate Prevention: Same rule won't trigger multiple times per day

Health Data Tracking

  • Automatic Sync: iOS app reads directly from Apple Health (HealthKit)
  • Real-time Dashboard: View today's activity with beautiful visualizations
  • Historical Summaries: Daily, weekly, and monthly health summaries
  • Progress Tracking: See how close you are to your next achievement

Reward Management

  • Pending Rewards: Achievements waiting for product selection
  • Approved Rewards: Products assigned and ready for purchase
  • Purchase Tracking: Complete reward history with status updates
  • Price Limits: Set maximum spend per achievement
  • Amazon Integration: Direct product links and affiliate tracking

Security & Privacy

  • JWT Authentication: Secure token-based auth across all platforms
  • Keychain Storage: iOS app stores tokens in secure Keychain
  • Password Hashing: bcrypt for secure password storage
  • Health Data Privacy: Data never shared with third parties
  • HTTPS Ready: Production-ready security configuration

Technology Stack

Component Technologies
Backend FastAPI, PostgreSQL, SQLAlchemy (async), Alembic, Redis, JWT
iOS App Swift 5.9+, SwiftUI, HealthKit, Keychain, async/await
Chrome Extension JavaScript ES6+, Chrome Extension Manifest v3, Content Scripts
Web Dashboard Next.js 16, React 19, TypeScript, Tailwind CSS, Radix UI, React Query, Zustand
Database PostgreSQL 16 with async connection pooling
Deployment Docker, Docker Compose, Vercel

Project Structure

Health_Achievement_Rewards/
├── health-rewards-backend/    # FastAPI backend
│   ├── app/
│   │   ├── api/routes/       # API endpoints (auth, health, rules, rewards)
│   │   ├── models/           # SQLAlchemy database models
│   │   ├── schemas/          # Pydantic validation schemas
│   │   ├── services/         # Business logic (rule engine, notifications)
│   │   └── utils/            # Security utilities
│   ├── alembic/              # Database migrations
│   ├── tests/                # pytest test suite
│   ├── docker-compose.yml    # Docker services config
│   ├── Dockerfile            # Container image
│   └── requirements.txt      # Python dependencies
│
├── ios-app/                  # SwiftUI iOS app
│   ├── HealthRewards/
│   │   ├── Models/           # API data models
│   │   ├── Services/         # API client, auth, HealthKit manager
│   │   ├── Views/            # SwiftUI views (dashboard, achievements, rewards)
│   │   ├── Info.plist        # App configuration
│   │   └── HealthRewards.entitlements
│   └── README.md
│
├── chrome-extension/         # Chrome extension
│   ├── manifest.json         # Extension config
│   ├── popup.*               # Main popup UI (HTML/JS/CSS)
│   ├── content.*             # Amazon page injection (JS/CSS)
│   ├── background.js         # Service worker
│   ├── api-client.js         # Backend API wrapper
│   └── icons/                # Extension icons
│
├── health-rewards-website/   # Next.js web dashboard
│   ├── src/
│   │   ├── app/              # Next.js App Router (pages)
│   │   │   ├── (auth)/       # Login, register, forgot-password
│   │   │   ├── (dashboard)/  # Protected dashboard routes
│   │   │   └── (marketing)/  # Public marketing pages
│   │   ├── components/       # React components
│   │   │   ├── dashboard/    # Dashboard components
│   │   │   ├── marketing/    # Marketing components
│   │   │   └── ui/           # Radix UI primitives
│   │   ├── hooks/            # Custom React hooks
│   │   ├── lib/api/          # API client functions
│   │   ├── stores/           # Zustand state stores
│   │   └── types/            # TypeScript interfaces
│   ├── public/               # Static assets
│   └── package.json          # Node.js dependencies
│
├── docs/                     # Documentation
│
└── README.md                 # This file

API Endpoints

Authentication

  • POST /api/v1/auth/register - Create new user account
  • POST /api/v1/auth/login - Login and receive JWT token
  • GET /api/v1/auth/me - Get current user details
  • GET /api/v1/auth/me/streak - Get current user streak info

Health Data

  • POST /api/v1/health/sync - Sync health metrics from iOS app
  • GET /api/v1/health/summary/{period} - Get aggregated health summary

Achievement Rules

  • POST /api/v1/rules - Create achievement rule
  • GET /api/v1/rules - List all rules for current user
  • GET /api/v1/rules/{id} - Get specific rule details
  • PUT /api/v1/rules/{id} - Update existing rule
  • DELETE /api/v1/rules/{id} - Delete rule
  • POST /api/v1/rules/{id}/test - Test rule without triggering
  • GET /api/v1/rules/{id}/progress - Get current progress toward goal
  • GET /api/v1/rules/{id}/tier-progress - Get tier progression for a rule
  • GET /api/v1/rules/tier-progress - Get tier progression for all rules

Rewards

  • GET /api/v1/rewards/pending - Get pending reward approvals
  • POST /api/v1/rewards/{id}/approve - Approve reward with product details
  • POST /api/v1/rewards/{id}/decline - Decline reward
  • POST /api/v1/rewards/{id}/complete - Mark reward as purchased
  • GET /api/v1/rewards/history - Get complete reward history

Wishlist/Products

  • GET /api/v1/wishlist - Get wishlist items
  • GET /api/v1/wishlist/next-item - Get next affordable item
  • GET /api/v1/wishlist/item/{asin} - Get product details by ASIN
  • GET /api/v1/wishlist/search - Search Amazon products
  • POST /api/v1/wishlist/generate-link - Generate affiliate link
  • POST /api/v1/wishlist/items/batch - Get details for multiple products

Full API documentation available at http://localhost:8000/docs (Swagger UI)

Database Schema

Users

Stores user accounts with authentication credentials and Amazon associate tags.

Sources

Tracks health data sources (iOS devices) for each user.

Health Data Points

Time-series storage of all health metrics (steps, calories, exercise, distance).

Rules

Achievement rules with trigger conditions (metric, operator, threshold, period) and reward configuration.

Executions

Records of triggered achievements with status tracking (pending → approved → completed).

User Rule Progress

Tracks tier progression (Bronze → Silver → Gold → Platinum) per user per rule.

Destinations

User reward destinations (Amazon wishlist URLs, gift card preferences).

Setup Guides

Development

Running Tests

Backend:

cd health-rewards-backend
pytest --cov=app --cov-report=html

iOS App:

# Open in Xcode and press ⌘U

Database Migrations

cd health-rewards-backend

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

# Apply migrations
alembic upgrade head

# Rollback
alembic downgrade -1

Debugging

Backend Logs:

docker-compose logs -f api

iOS App:

  • Xcode console shows all logs
  • Use breakpoints for step debugging

Chrome Extension:

  • Right-click extension icon → Inspect popup
  • F12 on Amazon pages for content script logs
  • chrome://extensions → service worker link for background logs

Deployment

Backend (Production)

Docker:

docker build -t health-rewards-api .
docker run -d -p 8000:8000 --env-file .env health-rewards-api

Cloud Platforms:

  • Railway: Connect GitHub repo, set env vars, auto-deploy
  • Render: Same process as Railway
  • AWS/GCP: Use managed PostgreSQL + container service

iOS App

TestFlight:

  1. Archive app in Xcode (Product → Archive)
  2. Distribute to App Store Connect
  3. Submit for TestFlight review
  4. Share with internal/external testers

App Store:

  1. Complete app review requirements
  2. Submit for App Store review
  3. Publish to App Store

Chrome Extension

Chrome Web Store:

  1. Create developer account ($5 fee)
  2. Package extension as .zip
  3. Upload to Chrome Web Store
  4. Submit for review
  5. Publish to store

Environment Variables

Backend requires these environment variables (see health-rewards-backend/.env.example):

Required:

  • DATABASE_URL - PostgreSQL connection string
  • SECRET_KEY - JWT secret key (32+ characters)

Optional:

  • AMAZON_ACCESS_KEY - Amazon Product Advertising API key
  • AMAZON_SECRET_KEY - Amazon PA-API secret
  • AMAZON_PARTNER_TAG - Amazon associate tag
  • SMTP_USER - Email for notifications
  • SMTP_PASSWORD - Email password
  • VAPID_PRIVATE_KEY - Web push private key
  • VAPID_PUBLIC_KEY - Web push public key

Troubleshooting

Backend won't start

  • Check PostgreSQL is running: docker-compose ps
  • Verify .env file exists with correct DATABASE_URL
  • Check port 8000 is not already in use

iOS app can't connect

  • Ensure backend is accessible on local network
  • Use your computer's IP address, not localhost
  • Check firewall allows connections on port 8000
  • Verify both devices on same WiFi network

Chrome extension login fails

  • Verify backend is running at http://localhost:8000
  • Check Settings in extension for correct API URL
  • Ensure account exists in backend database

HealthKit data shows zero

  • Verify data exists in Apple Health app
  • Check HealthKit permissions in Settings → Health
  • Try re-granting permissions to the app

Contributing

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

Roadmap

Phase 1 (Complete):

  • Backend API with health data ingestion
  • iOS app with HealthKit integration
  • Chrome extension with Amazon integration
  • Achievement rule engine
  • Reward approval workflow

Phase 2 (Complete):

  • Web dashboard (Next.js) with full feature set
  • Achievement management with multi-step wizard
  • Reward management with approval workflow
  • Health analytics and visualization
  • User settings and profile management
  • Marketing landing pages
  • Streak multipliers (Phase 2A) - 10%-100% bonus based on streak length
  • Achievement tiers (Phase 2B) - Bronze/Silver/Gold/Platinum progression
  • iOS audit fixes & accessibility (Phase 2C) - WCAG AA, privacy manifest
  • Chrome extension multiplier display (Phase 2D) - streak badges, boosted amounts

Phase 3 (Planned):

  • iOS app multiplier UI display (Phase 2E)
  • Background sync for iOS app
  • Push notifications for achievements
  • Amazon wishlist auto-sync
  • Multi-region Amazon support
  • Apple Watch companion app
  • Team challenges and leaderboards (backend + basic UI started)
  • Integration with Fitbit, Garmin
  • Custom reward types (gift cards, donations)
  • Advanced analytics dashboard
  • Family sharing features

License

This project is proprietary software. All rights reserved.

Support

For issues and questions:

  • GitHub Issues: Create an issue in the repository
  • Documentation: See individual component README files
  • API Docs: http://localhost:8000/docs (when backend is running)

Acknowledgments

Built with:

  • FastAPI - Modern Python web framework
  • Next.js - React framework for web dashboard
  • SwiftUI - Apple's declarative UI framework
  • HealthKit - Apple's health data framework
  • PostgreSQL - Advanced open source database
  • Docker - Containerization platform

Statistics

  • Lines of Code: ~15,000+
  • API Endpoints: 26
  • Database Tables: 7
  • Service Modules: 6 (rule engine, achievement tracker, amazon, notifications, multipliers, tiers)
  • Test Files: 7 (auth, rule engine, rules API, multipliers, tiers, integration)
  • Supported Health Metrics: 4 (steps, calories, exercise, distance)
  • Platforms: iOS 16+, Chrome Browser, Web (all modern browsers)
  • Web Dashboard Pages: 16 routes (auth, dashboard, settings, marketing)

Ready to turn your fitness achievements into rewards? See QUICKSTART.md to get started in 10 minutes!

About

hit your steps goal automatically get something off your wishlist from amazon

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors