# Google Login & GBP API — How It Works

> **📋 WHY THIS FILE EXISTS**: This is a HUMAN REFERENCE document that explains the TWO
> completely separate Google integrations in this project: (1) "Sign in with Google" for
> user login, and (2) the GBP Performance API for fetching business data. These are commonly
> confused. This file clarifies which credentials go where, what scopes are needed, and which
> steps require human action. **Flash does NOT read this file — it's for your understanding.**

## Two Separate Google Integrations (Don't Confuse Them!)

This project uses Google in TWO completely independent ways:

| # | Purpose | What It Does | When Needed |
| --- | --- | --- | --- |
| **1** | **User Login** (Sign in with Google) | Verifies WHO the user is (email/name) | Alternate login method |
| **2** | **GBP Data Access** (Business Profile API) | Fetches metrics, creates posts | Core dashboard functionality |

These use **different credentials**, **different scopes**, and **different flows**.

---

## Integration 1: Sign in with Google (User Login)

### What Happens (Login Flow)

```text
User clicks "Sign in with Google"
    → Browser redirects to accounts.google.com
    → User picks their Google account
    → Google asks: "Allow this app to see your email and name?"
    → User clicks "Allow"
    → Google redirects back to YOUR app with a temporary code
    → Your backend exchanges the code for the user's email + name
    → Backend checks: "Is this email in our users table?"
    → If yes: issue JWT token, log them in
    → If no: reject — "Contact your admin to be registered"
```

### Setup Steps for Login (HUMAN MUST DO)

1. Go to <https://console.cloud.google.com>
2. Select or create a project
3. Go to **APIs & Services → OAuth consent screen**
   - Choose "External"
   - App name: "GBP Dashboard"
   - Add your email as test user (while in testing mode)
4. Go to **APIs & Services → Credentials**
   - Click **Create Credentials → OAuth 2.0 Client ID**
   - Application type: **Web application**
   - Name: "GBP Dashboard Login"
   - Authorized redirect URIs: `http://localhost:8000/api/auth/google/callback`
5. Copy **Client ID** and **Client Secret** into your `.env` file

### Scopes Needed (Login Identity)

```text
openid
email
profile
```

These are basic identity scopes — NO special approval needed.

### Python Libraries (Login Auth)

```text
authlib    — handles the OAuth dance
httpx      — makes HTTP requests to Google
```

---

## Integration 2: Google Business Profile API (GBP Data)

### What Happens (Data Flow)

```text
Your backend server authenticates with Google (server-to-server)
    → Uses a Service Account key file
    → Calls the Performance API for each location
    → Gets metrics: views, clicks, calls, directions, reviews
    → Stores in your database
    → Frontend reads from YOUR database (not Google directly)
```

### Setup Steps for GBP API (HUMAN MUST DO)

#### Step A: Get API Access (THIS IS THE BOTTLENECK)

1. You MUST have a Google Business Profile that is **verified and active for 60+ days**
2. Go to <https://developers.google.com/my-business/content/prerequisites>
3. Submit the API access request form with your GCP Project Number
4. **Wait for Google to approve** (days to weeks — START THIS IMMEDIATELY)

#### Step B: Enable APIs

Once approved, go to Google Cloud Console → APIs & Services → Library, and enable:

- Business Profile Performance API
- My Business Account Management API  
- My Business Business Information API
- Google My Business API (for posts)

#### Step C: Create Service Account

1. Go to **IAM & Admin → Service Accounts**
2. Create a service account (e.g., `gbp-dashboard@your-project.iam.gserviceaccount.com`)
3. Create a key → Download JSON key file
4. Save as `backend/service_account.json`

#### Step D: Grant Access

1. Go to Google Business Profile Manager (business.google.com)
2. Go to the Fenesta organization/location group settings
3. Add the service account email as a **Manager**
4. Now the service account can read all locations under that group

### Scopes Needed (GBP Data Access)

```text
https://www.googleapis.com/auth/business.manage
```

This scope requires **Google's approval** (Step A above).

### Python Libraries (GBP API)

```text
google-api-python-client    — Google API client
google-auth                 — authentication
google-auth-oauthlib        — OAuth helper (for one-time setup)
```

### API Endpoints Used

| API | Endpoint | Purpose |
| --- | --- | --- |
| Business Information | `GET /v1/accounts/{id}/locations` | List all dealer locations |
| Performance | `GET /v1/locations/{id}:fetchMultiDailyMetricsTimeSeries` | Get metrics |
| My Business v4 | `POST /v4/accounts/{id}/locations/{id}/localPosts` | Create posts |

### Available Metrics

```text
BUSINESS_IMPRESSIONS_DESKTOP_SEARCH    → Search Views (Desktop)
BUSINESS_IMPRESSIONS_MOBILE_SEARCH     → Search Views (Mobile)
BUSINESS_IMPRESSIONS_DESKTOP_MAPS      → Map Views (Desktop)
BUSINESS_IMPRESSIONS_MOBILE_MAPS       → Map Views (Mobile)
WEBSITE_CLICKS                         → Website Clicks
CALL_CLICKS                            → Phone Calls
BUSINESS_DIRECTION_REQUESTS            → Direction Clicks  ✅ CONFIRMED
BUSINESS_CONVERSATIONS                 → Messages (future)
BUSINESS_BOOKINGS                      → Bookings (future)
```

---

## Alternate Login Path (If Google OAuth Is Not Set Up)

If the Google Cloud OAuth credentials are not configured yet, the system falls back to:

### Email + Password only

- Agency admin creates users with a generated temporary password
- User logs in with email + temp password
- Forced to change password on first login
- JWT-based session from there

This path works immediately with ZERO Google configuration. Google OAuth is purely optional/additive.

---

## Summary: What Needs Human Action

| Action | Blocking? | Timeline |
| --- | --- | --- |
| Create Google Cloud project | No (can use mock data) | 10 min |
| Set up OAuth consent screen | No (email login works without it) | 15 min |
| Create OAuth client credentials | No (alternate login path exists) | 5 min |
| **Apply for GBP API access** | **YES — blocks real data** | **Days to weeks** |
| Enable GBP APIs | YES (after approval) | 5 min |
| Create Service Account | YES (after approval) | 10 min |
| Add Service Account to GBP | YES (after approval) | 5 min |

**START THE API ACCESS APPLICATION ON DAY 1.** Everything else can be built and tested with mock data while waiting.
