# Google Sheets Auto-Sync - Setup Guide

**Implementation Status:** Code Complete ✅
**Remaining Tasks:** Manual Configuration Required

---

## What Has Been Implemented

All code files have been created and are ready to use:

✅ **Database Migration** - `database/migrations/2025_11_20_015207_add_google_sheets_columns_to_users_table.php`
✅ **User Model** - Updated with Google Sheets fields
✅ **GoogleSheetsService** - `app/Services/GoogleSheetsService.php`
✅ **GoogleAuthController** - `app/Http/Controllers/GoogleAuthController.php`
✅ **Queue Job** - `app/Jobs/SyncOrderToGoogleSheets.php`
✅ **Event Listener** - Added to `app/Observers/OrderObserver.php`
✅ **Settings UI** - `resources/views/settings/google-sheets.blade.php`
✅ **Routes** - Added to `routes/web.php`
✅ **Configuration** - Added to `config/services.php` and `.env.example`

---

## Setup Instructions

### Step 1: Install Google API Client Library

The Google API Client library needs to be installed. Run this command:

```bash
# Set longer timeout for extraction
composer config --global process-timeout 900

# Install the package
composer require google/apiclient:^2.0
```

If you encounter timeout errors, try:
```bash
COMPOSER_PROCESS_TIMEOUT=900 composer require google/apiclient:^2.0
```

Or install manually:
```bash
composer require google/apiclient:^2.0 --no-interaction --prefer-dist
```

---

### Step 2: Run Database Migration

Apply the database changes:

```bash
php artisan migrate
```

This will add the following columns to the `users` table:
- `google_sheet_id`
- `google_access_token`
- `google_refresh_token`
- `google_token_expires_at`
- `google_sheets_sync_enabled`
- `google_sheets_last_sync`
- `google_email`

---

### Step 3: Create Google Cloud Project

1. **Go to Google Cloud Console**
   - Visit: https://console.cloud.google.com/
   - Sign in with your Google account

2. **Create a New Project**
   - Click "Select a Project" → "New Project"
   - Project Name: `Multistore Order Sync` (or any name you prefer)
   - Click "Create"

3. **Enable Required APIs**
   - Go to "APIs & Services" → "Library"
   - Search and enable:
     - **Google Sheets API**
     - **Google Drive API**

4. **Create OAuth 2.0 Credentials**
   - Go to "APIs & Services" → "Credentials"
   - Click "Create Credentials" → "OAuth client ID"
   - Configure OAuth Consent Screen first (if prompted):
     - User Type: **External**
     - App Name: `Multistore Order Sync`
     - User Support Email: Your email
     - Developer Contact: Your email
     - Click "Save and Continue"
     - Scopes: Click "Add or Remove Scopes"
       - Add: `https://www.googleapis.com/auth/spreadsheets`
       - Add: `https://www.googleapis.com/auth/drive.file`
       - Add: `https://www.googleapis.com/auth/userinfo.email`
     - Click "Save and Continue"
     - Test Users: Add your email (optional for development)
     - Click "Save and Continue"

   - Back to Create OAuth Client ID:
     - Application Type: **Web Application**
     - Name: `Multistore Web Client`
     - Authorized Redirect URIs:
       - Development: `http://multistore.test/auth/google/callback`
       - Production: `https://yourdomain.com/auth/google/callback`
     - Click "Create"

5. **Copy Credentials**
   - You'll see a dialog with:
     - **Client ID** (looks like: `123456789-abcdefg.apps.googleusercontent.com`)
     - **Client Secret** (looks like: `GOCSPX-xyz123abc`)
   - Copy both values

---

### Step 4: Configure Environment Variables

Edit your `.env` file and add:

```env
GOOGLE_CLIENT_ID=your_client_id_here
GOOGLE_CLIENT_SECRET=your_client_secret_here
GOOGLE_REDIRECT_URI=http://multistore.test/auth/google/callback
```

**Important:**
- Replace `your_client_id_here` with the Client ID from Step 3
- Replace `your_client_secret_here` with the Client Secret from Step 3
- Change `http://multistore.test` to your actual domain in production

---

### Step 5: Clear Config Cache

```bash
php artisan config:clear
php artisan cache:clear
```

---

### Step 6: Start Queue Worker (Important!)

Google Sheets sync uses queue jobs for reliability. Start a queue worker:

```bash
php artisan queue:work
```

**For Production:**
Use Supervisor or Laravel Horizon to keep the queue worker running:

```bash
# Install Supervisor (Ubuntu/Debian)
sudo apt-get install supervisor

# Create config file: /etc/supervisor/conf.d/multistore-worker.conf
[program:multistore-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/multistore/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/path/to/multistore/storage/logs/worker.log
stopwaitsecs=3600

# Reload Supervisor
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start multistore-worker:*
```

---

## Testing the Integration

### Test 1: Access Settings Page

1. Login as a **seller** user
2. Navigate to: `http://multistore.test/settings/google-sheets`
3. You should see the Google Sheets Sync settings page

### Test 2: Connect Google Account

1. On the settings page, click "Connect Google Account"
2. You'll be redirected to Google OAuth consent screen
3. Select your Google account
4. Click "Allow" to grant permissions
5. You should be redirected back with success message
6. A Google Sheet should be created in your Google Drive

### Test 3: Create an Order

1. Go to sales page or checkout form
2. Create a new order
3. Within 5-10 seconds, check your Google Sheet
4. The order should appear as a new row

### Test 4: Update an Order

1. Edit an existing order (e.g., add tracking number)
2. Save the changes
3. Check your Google Sheet
4. The row should be updated with new data

---

## Troubleshooting

### Problem: "Google API Client library not installed"

**Solution:**
```bash
composer require google/apiclient:^2.0
```

### Problem: OAuth redirect not working

**Solution:**
1. Check that the redirect URI in Google Cloud Console matches exactly:
   - `http://multistore.test/auth/google/callback` (development)
   - `https://yourdomain.com/auth/google/callback` (production)
2. Run `php artisan config:clear`

### Problem: Orders not syncing

**Solution:**
1. Check queue worker is running: `php artisan queue:work`
2. Check logs: `storage/logs/laravel.log`
3. Verify seller has Google Sheets connected:
   ```sql
   SELECT id, name, google_sheets_sync_enabled, google_sheet_id FROM users WHERE role = 'seller';
   ```

### Problem: Token expired error

**Solution:**
This should auto-refresh. If it doesn't:
1. Disconnect and reconnect Google account
2. Check that `google_refresh_token` is stored in database

### Problem: Permission denied errors

**Solution:**
1. Verify APIs are enabled in Google Cloud Console
2. Check OAuth consent screen status (should be "Published" or "Testing")
3. Ensure user email is added to test users (if in testing mode)

---

## Security Checklist

Before going to production:

- [ ] Google Client ID and Secret are in `.env` (NOT in code)
- [ ] `.env` file is NOT committed to git
- [ ] HTTPS is enabled for production domain
- [ ] OAuth redirect URI uses HTTPS in production
- [ ] Google OAuth consent screen is configured properly
- [ ] Test with at least 2 different seller accounts
- [ ] Queue worker is running via Supervisor
- [ ] Error logging is enabled

---

## User Guide for Sellers

Share this with your sellers:

**How to Enable Google Sheets Sync:**

1. Login to your account
2. Go to Settings → Google Sheets Sync
3. Click "Connect Google Account"
4. Select your Gmail account and click "Allow"
5. Done! A Google Sheet will be created in your Drive
6. All future orders will automatically sync to your sheet

**How to View Your Orders:**

1. Open Google Drive (https://drive.google.com)
2. Look for a sheet named: `[Your Name] - Sales Orders - [Date]`
3. You can also access it from the mobile Google Sheets app

**How to Disconnect:**

1. Go to Settings → Google Sheets Sync
2. Click "Disconnect Google Account"
3. Note: Your existing sheet will remain in your Drive

---

## API Rate Limits

Google Sheets API has these limits:
- **300 requests per minute per project**
- **60 requests per minute per user**

Our implementation handles this by:
- Using queue jobs (prevents bursts)
- Adding 0.1 second delay between batch syncs
- Retry logic (3 attempts)

If you have high volume sellers (>50 orders/minute), consider:
- Upgrading to Google Workspace
- Batching updates (every 5 minutes instead of real-time)

---

## Next Steps

Once setup is complete:

1. **Test thoroughly** with test orders
2. **Train sellers** on how to use the feature
3. **Monitor logs** for any errors
4. **Set up alerts** for failed sync jobs
5. **Consider adding** to onboarding process for new sellers

---

## Support

If you encounter issues:

1. Check logs: `storage/logs/laravel.log`
2. Check queue status: `php artisan queue:failed`
3. Review Google Cloud Console logs
4. Check database: `select * from failed_jobs`

---

**Status:** Ready to Use! 🚀

Just complete Steps 1-6 above and you're good to go!
