# Google Sheets Troubleshooting

This guide covers common issues you might encounter with the Google Sheets integration and how to fix them.

## Orders Not Syncing

**Symptoms:**
- Created an order but it doesn't appear in Google Sheets
- Sheet is connected but no new orders show up
- Last sync timestamp not updating

**Possible Causes & Solutions:**

### 1. Queue Worker Not Running

The most common issue. Syncing happens in the background via Laravel queues.

**Check if worker is running:**

```bash
# On Linux/Mac
ps aux | grep "queue:work"

# On Windows
tasklist | findstr php
```

**If not running, start it:**

```bash
# Development
php artisan queue:work database --sleep=3 --tries=3

# Production (use Supervisor - see deployment docs)
sudo supervisorctl start laravel-worker:*
```

**Important:** Queue workers load code once when they start. If you update code, you must restart the worker:

```bash
# Kill the worker
killall php  # Linux/Mac
taskkill /F /IM php.exe  # Windows

# Start fresh worker
php artisan queue:work database --sleep=3 --tries=3
```

### 2. Sync Disabled for User

Check if the seller has sync enabled:

```bash
php artisan tinker
```

Then run:
```php
$user = App\Models\User::find(YOUR_USER_ID);
echo "Sync enabled: " . ($user->google_sheets_sync_enabled ? 'YES' : 'NO') . "\n";
echo "Sheet ID: " . $user->google_sheet_id . "\n";
```

If sync is disabled or sheet ID is empty, the seller needs to reconnect their Google account.

### 3. Check Failed Jobs

Sometimes jobs fail and end up in the failed jobs table:

```bash
# View failed jobs
php artisan queue:failed

# Retry all failed jobs
php artisan queue:retry all

# Clear failed jobs (after fixing the issue)
php artisan queue:flush
```

### 4. Check Laravel Logs

Detailed error messages are in the logs:

```bash
tail -50 storage/logs/laravel.log
```

Look for lines containing "Google Sheets" or "SyncOrderToGoogleSheets".

## Authentication Errors

**Error:** "Failed to authenticate with Google"

**Solutions:**

### Check Token Expiration

Tokens expire after a certain period. The system should auto-refresh them, but sometimes this fails.

**Fix:** Disconnect and reconnect the Google account:
1. Go to Settings > Google Sheets
2. Click "Disconnect"
3. Click "Connect Google Account" again
4. Authorize the app

### Verify Credentials

Make sure your `.env` file has the correct Google credentials:

```env
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URI=https://yourdomain.com/auth/google/callback
```

After changing `.env`:
```bash
php artisan config:clear
```

### Check Redirect URI

The redirect URI in Google Cloud Console must match exactly:

**Local:** `http://localhost/multistore/public/auth/google/callback`
**Production:** `https://yourdomain.com/auth/google/callback`

Note: No trailing slash, exact path match required.

## Rate Limit Errors

**Error:** "Quota exceeded" or "Rate limit exceeded"

Google Sheets API limits requests to 60 per minute per user.

**The system handles this automatically** with built-in delays and retries. However, if you're doing bulk syncs:

**Solutions:**

1. **Wait a few minutes** and try again
2. **Use smaller batches** - sync 10 orders at a time instead of 100
3. **Check the queue worker logs** - it will retry automatically with exponential backoff

**Monitor active syncs:**
```bash
# Check queue status
php artisan queue:monitor redis:default

# Watch queue worker output
tail -f storage/logs/worker.log
```

## Permission Errors

**Error:** "Insufficient Permission" or "Access denied"

**Causes:**

### APIs Not Enabled

Make sure you enabled both required APIs in Google Cloud Console:
- Google Sheets API
- Google Drive API

**How to check:**
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Select your project
3. Go to "APIs & Services" > "Enabled APIs & services"
4. Verify both APIs are listed

### Missing OAuth Scopes

The OAuth consent screen must have all three scopes:
- `https://www.googleapis.com/auth/spreadsheets`
- `https://www.googleapis.com/auth/drive.file`
- `https://www.googleapis.com/auth/userinfo.email`

**Fix:** Update OAuth consent screen in Google Cloud Console, then have users reconnect.

## Duplicate Orders in Sheet

**Symptom:** Same order appears multiple times

**Cause:** The duplicate detection relies on the Global Order ID in Column A. If the column structure was changed or the sheet was created before the latest updates, duplicates might occur.

**Fix:**

1. **Disconnect and reconnect** to create a fresh sheet with the correct structure
2. **Or manually fix the old sheet:**
   - Make sure Column A contains "Global Order ID"
   - Make sure Column B contains "Order Number"
   - Use the "Sync 10 Orders" button to update recent orders

## Old Column Structure

**Symptom:** Headers are correct but data appears in wrong columns

**Cause:** Your sheet was created before the column rearrangement update (2025-11-21).

**Solution 1 - Fresh Start (Recommended):**
1. Disconnect Google account
2. Reconnect (creates new sheet)
3. Use "Sync 10 Orders" to populate recent data
4. Old sheet remains in Google Drive for reference

**Solution 2 - Manual Fix:**
1. Open your existing Google Sheet
2. Manually swap Column A and Column B headers
3. Add "Notes" as Column T
4. Use "Sync 10 Orders" to update the data

## Missing Notes Column

**Symptom:** Notes don't appear in Column T

**Cause:** Sheet was created before the notes feature was added.

**Fix:**

The system checks for 20 columns (A through T). If your sheet only has 19 columns:

1. Add a header "Notes" in cell T1
2. Format it to match other headers (blue background, white text, bold)
3. Re-sync your orders using "Sync 10 Orders"

Or create a fresh sheet (disconnect and reconnect).

## Connection Lost

**Symptom:** Was working fine, then stopped

**Possible Causes:**

### User Revoked Access

Check if the user revoked access from their Google account:
1. Go to [Google Account Permissions](https://myaccount.google.com/permissions)
2. Look for your app name
3. If not listed, the user needs to reconnect

### Token Expired Without Refresh

Sometimes refresh tokens fail. Solution:
1. Disconnect and reconnect the Google account
2. Make sure the seller uses the same Gmail account

### Google Cloud Project Issues

Check if your Google Cloud project is still active:
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Select your project
3. Check if APIs are still enabled
4. Check if OAuth credentials still exist

## Manual Sync Fails

**Symptom:** Clicking "Sync 10 Orders" doesn't work

**Debug Steps:**

1. **Check browser console** for JavaScript errors (F12 > Console)
2. **Check Laravel logs** for errors
3. **Verify queue worker is running**
4. **Try syncing a single order manually:**

```bash
php artisan tinker
```

```php
$order = App\Models\Order::find(ORDER_ID);
$user = App\Models\User::find(USER_ID);
$service = new App\Services\GoogleSheetsService();
$result = $service->syncOrder($order, $user);
echo $result ? 'Success' : 'Failed';
```

If this works but the button doesn't, it's a frontend issue. Check browser console and Laravel logs.

## Diagnostic Commands

Use these commands to diagnose issues:

### Check User Settings

```bash
php artisan tinker

$user = App\Models\User::find(USER_ID);
echo "Sync Enabled: " . ($user->google_sheets_sync_enabled ? 'YES' : 'NO') . "\n";
echo "Sheet ID: " . $user->google_sheet_id . "\n";
echo "Email: " . $user->google_email . "\n";
echo "Last Sync: " . $user->google_sheets_last_sync . "\n";
echo "Token Expires: " . $user->google_token_expires_at . "\n";
```

### Check Queue Jobs

```bash
# See pending jobs
php artisan queue:monitor database:default

# See failed jobs
php artisan queue:failed

# Clear all failed jobs
php artisan queue:flush
```

### Test Google API Connection

```bash
php artisan tinker

$user = App\Models\User::find(USER_ID);
$service = new App\Services\GoogleSheetsService();

try {
    $client = $service->authenticate($user);
    echo "Authentication successful!\n";
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
```

## Getting More Help

If you're still stuck:

1. **Check Laravel logs:**
   ```bash
   tail -100 storage/logs/laravel.log | grep -i "google"
   ```

2. **Enable debug mode** (only on development):
   ```env
   APP_DEBUG=true
   ```

3. **Check queue worker logs:**
   ```bash
   tail -50 storage/logs/worker.log
   ```

4. **Review recent changes:**
   - See [Changelog](changelog.md) for recent updates
   - Check if you updated code without restarting queue workers

## Common Mistakes

1. **Forgetting to restart queue workers** after code updates
2. **Using wrong redirect URI** (trailing slash, wrong protocol)
3. **Not enabling both APIs** in Google Cloud Console
4. **Missing OAuth scopes** in consent screen
5. **Queue worker not running** on production server

## Next Steps

- [Setup Guide](setup.md) - Initial configuration
- [Features Guide](features.md) - How to use all features
- [Changelog](changelog.md) - Recent updates and fixes

---

**Last updated:** 2025-11-21
